package org.demo.test.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 双线程交替答应实现
 */
public class SwitchPrint {



    public static void main(String[] args) {
        Object lock = new Object();

        long start = System.currentTimeMillis();
        long times = 20000;

        /*Thread t1 = new Thread(()->{
            try {
                synchronized (lock) {
                    for (int i = 0; i < times; i++) {
                        System.out.println(i);
                        lock.notify();
                        if(i == (times-1)) break;
                        lock.wait();
                    }
                }
                System.out.println("1耗时："+(System.currentTimeMillis()-start));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(()->{
            try {
                synchronized (lock) {
                    for (int i = 0; i < times; i++) {
                        System.out.println(((char)('a'+i)));
                        lock.notify();
                        if(i == (times-1)) break;
                        lock.wait();
                    }
                }
                System.out.println("2耗时："+(System.currentTimeMillis()-start));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t2.start();
        t1.start();*/

        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();

        Thread t1 = new Thread(()->{
            try {
                reentrantLock.lock();
                for (int i = 0; i < times; i++) {
                    System.out.println(i);
                    condition.signalAll();
                    if(i == (times-1)) break;
                    condition.await();
                }
                reentrantLock.unlock();
                System.out.println("1耗时："+(System.currentTimeMillis()-start));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(()->{
            try {
                reentrantLock.lock();
                    for (int i = 0; i < times; i++) {
                        System.out.println(((char)('a'+i)));
                        condition.signalAll();
                        if(i == (times-1)) break;
                        condition.await();
                    }
                reentrantLock.unlock();
                System.out.println("2耗时："+(System.currentTimeMillis()-start));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t2.start();
        t1.start();

        try {
            t1.join();
            t2.join();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
